package org.btik.lightweb.interceptor;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;

import java.io.IOException;

import static org.btik.lightweb.interceptor.UserLoginInterceptor.checkUserLoginAnd;

/**
 * 拦截websocket的upgrade请求
 * 判断其是否登录，而无需再加其他参数
 *
 * @author lustre
 * @since 2023/6/19 1:08
 */
@WebFilter(urlPatterns = "/control", filterName = "wsControlFilter")
@Order(1)
public class WebSockFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        if (!(request instanceof HttpServletRequest httpServletRequest)
                || !(response instanceof HttpServletResponse httpServletResponse)) {
            chain.doFilter(request, response);
            return;
        }
        // 检查用户是否登录，登录用户是否有效
        if (!checkUserLoginAnd(httpServletRequest, httpServletResponse,
                (userVo) -> true)) {
            return;
        }

        chain.doFilter(request, response);


    }
}
